package future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Future模式
 * 有返回值 callable fureturetask
 * 异步执行 需要返回值时才阻塞
 *
 * 传统的Runnable
 * 无返回值 主线程得join等待完成
 * 2020-11-06 14:05
 */
public class MyFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        Callable cal = new Callable(){
            @Override
            public String call() throws Exception {
                try{
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return "凉菜准备完毕";
            }
        };
        FutureTask<String> ft1 = new FutureTask<String>(cal);
        new Thread(ft1).start();

        Callable cal2 = new Callable(){
            @Override
            public String call() throws Exception {
                try{
                    Thread.sleep(1000 * 3);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return "包子准备完毕";
            }
        };
        FutureTask<String> ft2 = new FutureTask<String>(cal2);
        new Thread(ft2).start();

        System.out.println(ft1.get());
        System.out.println(ft2.get());
        long end = System.currentTimeMillis();
        System.out.println("完毕时间" + (end - start));
    }
}
